package flyingpig.data.dao;

// default package
// Generated 2010-5-2 9:39:48 by Hibernate Tools 3.3.0.GA

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

import sun.util.resources.CalendarData;

import flyingpig.data.domain.JobPage;
import flyingpig.hibernate.HibernateUtil;

/**
 * Home object for domain model class JobPage.
 * 
 * @see .JobPage
 * @author Hibernate Tools
 */
public class JobPageHome {

    private static final Log log = LogFactory.getLog(JobPageHome.class);

    private final SessionFactory sessionFactory = getSessionFactory();

    protected SessionFactory getSessionFactory() {
        try {
            return HibernateUtil.getSessionFactory();
        } catch (Exception e) {
            log.error("Could not locate SessionFactory in JNDI", e);
            throw new IllegalStateException(
                    "Could not locate SessionFactory in JNDI");
        }
    }

    public void persist(JobPage transientInstance) {
        log.debug("persisting JobPage instance");
        try {
            HibernateUtil.getCurrentSession().persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(JobPage instance) {
        log.debug("attaching dirty JobPage instance");
        try {
            HibernateUtil.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(JobPage instance) {
        log.debug("attaching clean JobPage instance");
        try {
            HibernateUtil.getCurrentSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void delete(JobPage persistentInstance) {
        log.debug("deleting JobPage instance");
        try {
            HibernateUtil.getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public JobPage merge(JobPage detachedInstance) {
        log.debug("merging JobPage instance");
        try {
            JobPage result = (JobPage) HibernateUtil.getCurrentSession().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public JobPage findById(int id) {
        log.debug("getting JobPage instance with id: " + id);
        try {
            JobPage instance = (JobPage) HibernateUtil.getCurrentSession().get(
                    "flyingpig.data.domain.JobPage", id);
            if (instance == null) {
                log.debug("get successful, no instance found");
            } else {
                log.debug("get successful, instance found");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(JobPage instance) {
        log.debug("finding JobPage instance by example");
        try {
            List results = HibernateUtil.getCurrentSession().createCriteria(
                    "flyingpig.data.domain.JobPage").add(
                    Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public JobPage findOnePageBySearchJobID(int searchJobID) {

        log.debug("finding one JobPage instance by searchJobID");
        Query q;
        if (searchJobID <= 0) {
            q = HibernateUtil.getCurrentSession().createQuery(
                    "from JobPage as S where S.pageState = 'INCOMPLETE'");
        } else {
            q = HibernateUtil
                    .getCurrentSession()
                    .createQuery(
                            "from JobPage as S where S.searchJobId = :searchJobID and S.pageState = 'INCOMPLETE'");
            q.setInteger("searchJobID", searchJobID);
        }

        q.setFirstResult(0);
        q.setMaxResults(1);
        List jobPages = q.list();
        if(jobPages == null || jobPages.size() == 0){
            return null;
        }
        
        return (JobPage)jobPages.get(0);
    }
    
	public List findDeadPage(int hoursAgo) {
		log.info("finding dead JobPage...");
		try {
			Query q = HibernateUtil
					.getCurrentSession()
					.createQuery(
							"from JobPage as J where J.pageState = :pageState and J.lastUpdate < :lastUpdate");
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.HOUR_OF_DAY, -1 * hoursAgo); // 当前时间的hoursAgo小时前
			Date lastUpdate = cal.getTime();
			log.info("check time: " + lastUpdate);
			q.setTimestamp("lastUpdate", lastUpdate);
			q.setString("pageState", "DOWNLOADING");

			q.setFirstResult(0);
			q.setMaxResults(100);
			return q.list();
			
		} catch (RuntimeException re) {
			log.error("find dead page failed", re);
			throw re;
		}
	}
}
